import { MessageBox } from 'element-ui'
import store from '@/store'
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'
import { Loading } from 'element-ui';

/*
  定义计算间隔年数和天数的函数
  @inputDate 传入时间
*/
// 
export function calculateDateDifference(inputDate) {
  const input = new Date(inputDate);
  const now = new Date();
  // 计算相差总毫秒数
  const differenceInMilliseconds = Math.abs(now - input);
  // 转换为天数（一天等于1000 * 60 * 60 * 24毫秒）
  const differenceInDays = Math.floor(differenceInMilliseconds / (1000 * 60 * 60 * 24));
  // 计算完整年数（一年按365天计算）
  const fullYears = Math.floor(differenceInDays / 365);
  let result = '';
  if (fullYears > 0) {
    // 如果有完整的年份
    result = `${fullYears}年`;
    
    // 计算剩余天数
    const remainingDays = differenceInDays % 365;
    if (remainingDays > 0) {
        result += `${remainingDays}天`;
    }
  } else {
    // 如果没有完整的年份，只显示天数
    result = `${differenceInDays}天`;
  }
  return result;
}


/*
  @Dom DOM元素
  @title pdf文件名
*/
export function htmlToPdf (Dom, title) {
  const elloading = Loading.service({
    lock: true,
    text: 'PDF生成中...',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)',
    // target: Dom,
  });

  html2Canvas(Dom, {
    allowTaint: true,
  }).then(function (canvas) {


    let contentWidth = canvas.width
    let contentHeight = canvas.height
    let pageHeight = contentWidth / 592.28 * 841.89
    let leftHeight = contentHeight
    let position = 0
    let imgWidth = 595.28
    let imgHeight = 592.28 / contentWidth * contentHeight
    let pageData = canvas.toDataURL('image/jpeg', 1.0)
    let PDF = new JsPDF('', 'pt', 'a4')
    let index = 0
    if (leftHeight < pageHeight) {
      PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
    } else {

      while (leftHeight > 0) {
        PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
        leftHeight -= pageHeight

        position -= 841.89 - index * 2

        if (leftHeight > 0) {
          PDF.addPage()
        }
        index++
      }
    }
    PDF.save(title + '.pdf')
    elloading.close();

  }
  )
}

/**
 * htmlToPdf 不自动分页
 * @param {HTMLElement[]} Doms - DOM元素数组，每个元素代表PDF的一页
 * @param {string} title - PDF文件名
 */

export async function pageHtmlToPdf(Doms, title) {



  const pdf = new JsPDF('', 'pt', 'a4');
  let index = 0;
  index

  // 使用Promise.all等待所有html2canvas操作完成
  const imagesPromises = Doms.map(async (Dom) => {
    const canvas = await html2Canvas(Dom, { allowTaint: true });
    return canvas.toDataURL('image/jpeg', 1.0);
  });

  const imagesData = await Promise.all(imagesPromises);

  // 假设每个图像都是A4大小，从页面顶部开始
  const pageHeight = 595.28; // A4页面高度
  const imgWidth = 595.28; // 图像宽度
  const imgHeight = 841.89; // 图像高度
  pageHeight

  imagesData.forEach((imgData,index) => {
    if (index>0) {
      pdf.addPage();
      console.log('addPage',index);
    }
    pdf.addImage(imgData, 'JPEG', 0, 0, imgWidth, imgHeight); // 将图像放置在页面顶部
    index++;
  });

  pdf.save(title + '.pdf');


}




/**
 * 生成随机字符串
 *@param length  生成的长度
 */
export function generateRandomString (length) {
  let result = '';
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  const charactersLength = characters.length;
  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
  }
  return result;
}
/**
 * 获取今年和去年年份
 *
 */
export function getYear () {
  var d1 = new Date()
  return {
    thisYear: d1.getFullYear(),
    lastYear: Number(d1.getFullYear()) - 1,
    qYear: Number(d1.getFullYear()) - 2
  }
}

/**
 * 判断是否HTTP
 * @param url  判断是否路径
 */
export function ishttp (url) {
  return url.indexOf('http://') !== -1 || url.indexOf('https://') !== -1
}

export function getImgUrl (url) {
  let flag = ishttp(url)
  return !flag ? baseImgUrl + url : url
}

/**
 * echarts大小自适应 sizeAdjust(14)
 * @param size 大小 单位px
 * @returns
 */
export function sizeAdjust (size) {
  let clientWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth
  if (!clientWidth) return
  let fontSize = clientWidth / 1920
  return Number((size * fontSize).toFixed(2))
}

/**
 * 千分位显示处理
 * @param num  值
 * @param n  保留小数位数
 * @returns String
 */
export function formatNum (num, n = 2) {
  if (num) {
    num = parseFloat(Number(num).toFixed(n))
    let [integer, decimal] = String.prototype.split.call(num, '.')
    integer = integer.replace(/\d(?=(\d{3})+$)/g, '$&,') // 正则先行断言
    return `${integer}${decimal ? '.' + decimal : ''}`
  } else {
    return 0
  }
}


// 获取图片和附件地址  附件传type
export function getFileList (ossIds, type = '') {
  return new Promise(resolve => {
    downloadOss(ossIds).then((res) => {
      // if (res.code == 200) {
      let arr = res.data.map((item) => {
        let obj = {
          url: item.url,
          ossId: item.ossId,
          fileSuffix: item.fileSuffix
        }
        if (type) {
          obj.name = item.originalName
        }
        return obj
      })
      resolve(arr)
      // }
    })
  })
}

/**
 * 通过id查找树节点
 * @param tree 查找的树
 * @param children  树的children 文本型
 * @param key 树的key值 文本型
 * @param id 查找的key值 文本型
 */
export function deepQuery (tree, children = 'children', key = 'id', id) {
  var stark = []
  stark = stark.concat(tree)
  while (stark.length) {
    var temp = stark.shift()
    if (temp[children]) {
      stark = temp[children].concat(stark)
    }
    if (id == temp[key]) {
      return temp
    }
  }
}

/**
 * 获取随机26个字母
 *  @param n 循环的树
 */
export function randomCoding (n = 6) {
  //创建26个字母数组
  var arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  var idvalue = ''
  // var n = 6;//这个值可以改变的，对应的生成多少个字母，根据自己需求所改
  for (var i = 0; i < n; i++) {
    idvalue += arr[Math.floor(Math.random() * 26)]
  }
  return idvalue
}




//远程上传-文件下载
export function downloadFileBlob (ossId, fileSuffix, name) {
  download(ossId).then(response => {
    const type = {
      '.xls': 'application/vnd.ms-excel',
      '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      '.jpg': 'image/jpeg',
      '.jpeg': 'image/jpeg',
      '.doc': 'application/msword',
      '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      '.pdf': 'application/pdf'
    }
    const blob = new Blob([response], { type: type[fileSuffix] }) // 为blob设置文件类型
    const url = window.URL.createObjectURL(blob) //创建一个临时的url指向blob对象
    let a = document.createElement('a')
    a.href = url
    a.download = name
    a.click()
    // 释放这个临时的对象url
    window.URL.revokeObjectURL(url)
  }).catch(error => {
    console.error(error)
  })
}






//数字转汉字大写
/**
 * 将人民币金额转换为中文大写金额
 * @param {string|number} money - 待转换的人民币金额
 * @returns {string} - 转换后的中文大写金额
 */
export function moneyToUppercase (money) {
  let cnNums = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']  // 汉字的数字
  let cnIntRadice = ['', '拾', '佰', '仟'] // 基本单位
  let cnIntUnits = ['', '万', '亿', '兆']  // 对应整数部分扩展单位
  let cnDecUnits = ['角', '分', '毫', '厘'] // 对应小数部分单位
  let cnInteger = '整'  // 整数金额时后面跟的字符
  let cnIntLast = '元'  // 整数完以后的单位
  // 最大处理的数字
  let maxNum = 999999999999999.9999
  let integerNum  // 金额整数部分
  let decimalNum  // 金额小数部分
  // 输出的中文金额字符串
  let chineseStr = ''
  let parts   // 分离金额后用的数组，预定义

  if (money === '') {
    return ''
  }

  money = parseFloat(money)

  if (money >= maxNum) {
    // 超出最大处理数字
    return '超出最大处理数字'
  }

  if (money === 0) {
    chineseStr = cnNums[0] + cnIntLast + cnInteger
    return chineseStr
  }
  // 四舍五入保留两位小数, 转换为字符串
  money = Math.round(money * 10000).toString()
  integerNum = money.substr(0, money.length - 4)
  decimalNum = money.substr(money.length - 4)

  // 获取整型部分转换
  if (parseInt(integerNum, 10) > 0) {
    let zeroCount = 0
    let IntLen = integerNum.length
    for (let i = 0; i < IntLen; i++) {
      let n = integerNum.substr(i, 1)
      let p = IntLen - i - 1
      let q = p / 4
      let m = p % 4

      if (n === '0') {
        zeroCount++
      } else {
        if (zeroCount > 0) {
          chineseStr += cnNums[0]
        }
        // 归零
        zeroCount = 0
        chineseStr += cnNums[parseInt(n)] + cnIntRadice[m]
      }

      if (m === 0 && zeroCount < 4) {
        chineseStr += cnIntUnits[q]
      }
    }
    chineseStr += cnIntLast
  }

  // 小数部分
  if (decimalNum !== '') {
    let decLen = decimalNum.length
    for (let i = 0; i < decLen; i++) {
      let n = decimalNum.substr(i, 1)

      if (n !== '0') {
        chineseStr += cnNums[Number(n)] + cnDecUnits[i]
      }
    }
  }

  if (chineseStr === '') {
    chineseStr += cnNums[0] + cnIntLast + cnInteger
  } else if (decimalNum === '' || /^0*$/.test(decimalNum)) {
    chineseStr += cnInteger
  }

  return chineseStr
}




